package net.xju_springJdbc19_20.dao;

import net.xju_springJdbc19_20.entity.Stu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

@Repository
public class StuDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional(readOnly = true)
    public List<Stu> findAll() {
        String sql = "select * from newtable";
        BeanPropertyRowMapper<Stu> rowMapper = new BeanPropertyRowMapper<>(Stu.class);
        return jdbcTemplate.query(sql, rowMapper);
    }

    @Transactional(timeout = 2,rollbackFor = Exception.class)
    public Integer insert(Stu stu) throws FileNotFoundException {
//        try {
//            Thread.sleep(4000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        String sql = "insert into newtable(name,sn) values(?,?)";
        int update = jdbcTemplate.update(sql, stu.getName(), stu.getSn());
//        int a = 10 / 0;
            new FileInputStream("xx");

        return update;
    }
}

